# coding: utf-8
import os
import web
import datetime
from web import form

import db
import skate
from config import DIR, app
from libs import *

__all__ = ['feedback', 'feedback_reply']

class feedback:

    feedback_form = form.Form(
            form.Textbox('username', form.notnull, description="名字"),
            form.Textarea('descr', form.notnull, description="内容"),
            )
    
    def GET(self):
        input = web.input(offset='None')
        limit = app.page_limit
        offset = None
        feedbacks = None

        try:
            offset = int(input.offset)
        except:
            offset = 0

        f = self.feedback_form()
        if skate.session.id != -1:
            f['username'].value = skate.session.user

        fb_size = db.get_count("feedback")
        feedbacks = list(db.get_feedbacks(limit, offset))

        page_split = page_split_up(fb_size, offset, limit, app.page_url)

        return skate.render.feedback(feedbacks[:limit], offset, limit, page_split, f)
        
    def POST(self):
        f = self.feedback_form()
        if not f.validates():
            skate.session.show_msg = True
            skate.session.msg = "填写不正确"
            raise web.seeother("feedback")
        
        username = f['username'].value
        descr = f['descr'].value
        ip = web.ctx.ip

        db.new_feedback(username, descr, ip)

        skate.session.show_msg = True
        skate.session.msg = "反馈发表成功"

        return web.seeother("feedback")

class feedback_reply:
    reply_form = form.Form(
            form.Textarea('descr', form.notnull, description="内容"),
            form.Hidden('fdid', description=''),
            )

    def ERROR(self, msg):
        skate.session.show_msg = True
        skate.session.msg = msg

    def permission_check(self):
        try:
            if skate.session.super == False:
                raise
        except:
            self.ERROR("你没有权限回复")
            return web.seeother('feedback')

    def GET(self):
        self.permission_check()
        input = web.input(fdid=None)

        if input.fdid:
            try:
                fdid = int(input.fdid)
                feedback = db.get_feedback(fdid)
            except:
                raise
                self.ERROR("反馈不存在")
                return web.notfound()
            else:
                f = self.reply_form()
                f['fdid'].value = fdid
                return skate.render.feedback_reply(f)
        else:
            self.ERROR("反馈不存在")
            return web.notfound()

    def POST(self):
        self.permission_check()
        f = self.reply_form()
        if not f.validates():
            self.ERROR("填写错误")
            return web.seeother("feedback_reply?fdid=%s" % f['fdid'].value)

        fdid = int(f['fdid'].value)
        descr = f['descr'].value

        db.update_feedback_reply(fdid, descr)

        skate.session.show_msg = True
        skate.session.msg = "反馈发表成功"

        return web.seeother("feedback")
